﻿using MD5Hash;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace B.S.BasicData.Api.Read.Extensions
{

    /// <summary>
    /// 扩展方法工具类
    /// </summary>
    public static class Utilss
    {
        /// <summary>
        /// 生成盐值
        /// </summary>
        /// <returns></returns>
        public static string CreateSalt(this object o) { 
            return Guid.NewGuid().ToString("N").GetMD5();//还有很多其他加密方式
        }

        /// <summary>
        /// 生成刷新token的方法
        /// </summary>
        /// <returns></returns>
        public static string CreateFreshToken(this object o)
        {
            return Guid.NewGuid().ToString("N");
        }




        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <param name="o"></param>
        /// <param name="accountName">账号</param>
        /// <param name="roleName">角色名称</param>
        /// <param name="realName">真实姓名</param>
        /// <returns>jwt-token</returns>
        public static string CreateTokenString(this object o,string accountName, string roleName, string realName)
        {
            //荷载内容
            var claims = new[] { new Claim("accountName", accountName), new Claim("roleName", roleName), new Claim("realName", realName), };
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddSeconds(8), // 一天后过期
                signingCredentials: signingCredentials,
                claims: claims
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }



    }
}
